package com.tao.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.base.feignClient.CheckCodeClient;
import com.tao.ucenter.mapper.UserMapper;
import com.tao.ucenter.model.dto.AuthParamsDto;
import com.tao.ucenter.model.dto.UserExt;
import com.tao.ucenter.model.po.User;
import com.tao.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 密码认证接口
 * </p>
 *
 * @author taohongrun
 * @since 2024/11/23
 */
@Service("password_authservice")
public class PasswordAuthService implements AuthService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserMapper xcUserMapper;

    @Autowired
    CheckCodeClient checkCodeClient;

    @Override
    public UserExt execute(AuthParamsDto authParamsDto) {

        //账号
        String username = authParamsDto.getUsername();
        //输入的验证码
        String checkCode = authParamsDto.getCheckcode();
        //验证码的key
        String checkCodeKey = authParamsDto.getCheckcodekey();

        if(checkCode ==null) throw new RuntimeException("请输入验证码");
        //校验验证码
        Boolean verify = null;
        try {
            verify=checkCodeClient.verify(checkCodeKey,checkCode);
        } catch (Exception e) {
            throw new RuntimeException("验证码校验过程出错");
        }
        //null和false都是错误
        if(verify==null||verify==false) {
            throw new RuntimeException("验证码错误");
        }

        //根据用户名和密码判断是否正确
        User user = xcUserMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(user==null){
            //返回空表示用户不存在
            throw new RuntimeException("账号不存在");
        }
        UserExt xcUserExt = new UserExt();
        BeanUtils.copyProperties(user,xcUserExt);
        //校验密码
        //取出数据库存储的正确密码
        String passwordDb  =user.getPassword();
        String passwordForm = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if(!matches){
            throw new RuntimeException("账号或密码错误");
        }
        return xcUserExt;
    }

}
